//
//  MGConfigManager.m
//  MoneyGoal_iOS
//
//  Created by yyb on 2022/8/31.
//  Copyright © 2022 Moneyease CO,. LTD. All rights reserved.
//

#import "MGConfigManager.h"
#import <StoreKit/SKStoreReviewController.h>

@implementation MGConfigManager

+ (MGConfigManager *)shared
{
    static MGConfigManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[MGConfigManager alloc] init];
    });
    return manager;
}

- (void)initialize
{
    self.dataModel = [[MGConfigModel alloc] init];
    
    NSString *savePath = [MGFileManager.shared directoryWithSubPath:@"Config"];
    NSData *data = [[NSFileManager defaultManager] contentsAtPath:savePath];
    
    if (data) {
        self.dataModel = [MGConfigModel yy_modelWithJSON:data];
    } else {
        [self syncConfigModel];
    }
}

- (void)syncConfigModel
{
    NSData *data = [self.dataModel yy_modelToJSONData];
    if (data) {
        NSString *savePath = [MGFileManager.shared directoryWithSubPath:@"Config"];
        [data writeToFile:savePath atomically:YES];
    }
}

- (void)handleCommentApp
{
    if (!self.dataModel.isCommented) {
        if (self.dataModel.createCount >= 3) {
            [SKStoreReviewController requestReview];
            self.dataModel.isCommented = YES;
            [self syncConfigModel];
        } else {
            self.dataModel.createCount ++;
            [self syncConfigModel];
        }
    }
}

- (void)handleChangeUser:(MGUserModel *)user
{
    self.dataModel.userModel = user;
    [self syncConfigModel];
}

- (void)configWithBlock:(void (^)(MGConfigModel * _Nonnull))configBlock
{
    if (configBlock) {
        configBlock(self.dataModel);
    }
    [self syncConfigModel];
}

@end
